import java.util.Arrays;

public class Solution611 {

    public int triangleNumber(int[] nums) {
        Arrays.sort(nums);
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                int sum = nums[i] + nums[j];
                int left = j+1, right = nums.length-1;
                int k = j;
                while(left<=right){
                    int mid = left + (right-left)/2;
                    if(nums[mid] < sum){
                        k = mid;
                        left = mid + 1;
                    }
                    else{
                        right = mid - 1;
                    }
                }
                res += k - j;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution611 s = new Solution611();
        System.out.println(s.triangleNumber(new int[]{34,75,96,10,60,70,70,45}));
        System.out.println(s.triangleNumber(new int[]{2,2,3,4}));
    }
}
